import { H3Event } from 'h3'
import jwt from 'jsonwebtoken';

const TOKEN_TYPE = 'Bearer'

const extractToken = (authHeaderValue: string) => {
  const [, token] = authHeaderValue.split(`${TOKEN_TYPE} `)
  return token
}

const ensureAuth = async (event: H3Event) => {
  const authHeaderValue = getRequestHeader(event, 'authorization')
  if (typeof authHeaderValue === 'undefined') {
    throw createError({ statusCode: 403, statusMessage: 'Need to pass valid Bearer-authorization header to access this endpoint' })
  }

  const extractedToken = extractToken(authHeaderValue)
  try {
    let userInfo = await jwt.decode(extractedToken)
   
    return userInfo
  } catch (error) {
    console.error('Login failed. Here\'s the raw error:', error)
    throw createError({ statusCode: 403, statusMessage: 'You must be logged in to use this endpoint' })
  }
}
type SessionData = {
  id: string
  username: string
  nickname: string
  realname: string
  avatar: string
  labels: string
  phone: string
  beInvitedCode: string
  inviteCode: string
  PythonCourseVIP: string
  score: number
  challengeVIP: number
  isCheckIn: boolean
  goodsUrl: string
  userGoods: [any]
}
export default eventHandler(async (event: any) => {
  const user: SessionData = await ensureAuth(event)
  return user
})
